package com.qianniu.napi.admin.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.ObjectUtil;
import com.qianniu.napi.common.util.SpringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 商家
 * </p>
 *
 * @author chenxuebin
 * @since 2018-06-17
 */
@RestController
public class MerchantController {

    private static final Logger logger = LoggerFactory.getLogger(MerchantController.class);

    @Autowired
    private IMerchantService merchantService;
    @Autowired
    private IConfigService configService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IAccountService accountService;
    @Autowired
    private IAddressService addressService;
    @Autowired
    private INoticeService noticeService;
    @Autowired
    private IJifenService jifenService;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IUserRoleService userRoleService;
    @Autowired
    private IMconfigExtService mconfigExtService;
    @Autowired
    private IStoreService storeService;

    @RequestMapping("/api/merchant/setting")
    @ResponseBody
    public Jinfo setting(@RequestParam(value = "v", required = false) Integer version
            , @RequestParam(value = "isadmin", required = false) Integer isadmin
            , @RequestParam(value = "type", required = false) String type
            , @RequestParam(value = "extra", required = false) String extra
            , @RequestParam(value = "buy", required = false) Integer buy
            , @RequestParam(value = "mchpstype", required = false) Integer mchpstype
            , @RequestParam(value = "gtype", required = false) Integer gtype) {

        Jinfo json = new Jinfo();
        Long mpid = ObjectUtil.getMpid();
        MerchantConfig config = redisService.getMconfig();
//        返回会员账户信息
        if (buy != null && buy == 1 && config != null && config.getIsMember() == 1) {

            logger.debug(">>>merchant setting config.isMember=true");
            User user = userService.selectById(ObjectUtil.getUid());
            config.setIsMember(user.getIsMember());

            Account account = accountService.selectOne(new EntityWrapper<Account>().eq("uid", ObjectUtil.getUid()));
            if (user.getIsMember() == 1 && account != null) {

                config.setAccount(account.getAmount().add(account.getMamount())); // 可用余额
                if (config.getIsEcashCard() == 1) config.setIsEcashCard(user.getIsEcashCard());
                else config.setIsEcashCard(-1);


                config.setDiscount(user.getDiscount() != null ? user.getDiscount() : config.getMemberDiscountRate()); // 会员折扣
                if (config.getDiscount().intValue() == 1) config.setDiscount(null);// 100折=无折扣=没辙
            } else {
                config.setIsEcashCard(-1);
            }
        }
        Jifen jifen = jifenService.selectOne(new EntityWrapper<Jifen>().eq("uid", ObjectUtil.getUid()));
        logger.info(">>>>>>>>>>>>>>>>>>>>>>jifen=" + jifen);

        //====待完善jifen.getTotal().intValue()
        config.setJfmount(jifen != null && jifen.getTotal() != null ? jifen.getTotal() : new BigDecimal(0));
        // 3:到店服务+返回用户默认地址
        if (gtype != null && config != null) {
            Address addr = addressService.selectOne(new EntityWrapper<Address>()
                    .eq("is_default", 1)
                    .eq("uid", ObjectUtil.getUid()));
            if (addr == null){
                addr = new Address();
                addr.setAddress("测试地址");
            }
            config.setDefaultAddr(addr);
        }
//        返回通知信息
        if (!Strings.isNullOrEmpty(type) && type.equals("notice") && config.getIsNotice() == 1) {
            Wrapper<Notice> entity = new EntityWrapper<Notice>();
            entity.eq("mid", ObjectUtil.getMid());
            entity.eq("state", 1);
            entity.orderBy("id", false);
            List<Notice> list = noticeService.selectList(entity);
            json.setExtra(list);
        }
        //返回关于信息
        if (!Strings.isNullOrEmpty(type) && type.equals("about")) {

            Wrapper<Notice> entity = new EntityWrapper<Notice>();
            entity.eq("mid", ObjectUtil.getMid());
            entity.eq("state", 1);
            entity.orderBy("id", false);
            List<Notice> list = noticeService.selectList(entity);
            json.setExtra(list);
        }
        //返回应用版本号，用于上线审查
        if (isadmin != null && isadmin == 1 && version != null && version > 0) {
            MconfigExt mconfigExt = mconfigExtService.selectById(mpid);
            if (mconfigExt != null) {
                json.setExtra(version > mconfigExt.getVersion());
            }
        }
        //返回快递类型
        MerchantConfig mconfig = redisService.getMconfig();

        if (!Strings.isNullOrEmpty(extra) && extra.lastIndexOf("pstype") >= 0
                && mconfig.getPstype() != null && (mconfig.getPstype() == 1||mconfig.getPstype() == 2)) {
            //获取快递公司
            List<Config> kuaidi = configService.selectList(new EntityWrapper<Config>().setSqlSelect("name,code")
                    .eq("mpid", mpid)
                    .eq("pcode", "kuaidibianma").orderBy("sort"));
            json.setData(kuaidi);
        }
        //平台型商家查询《参数：mchpstype》
        //根据商家自己的默认配送方式来决定配送
        if (mchpstype != null && mchpstype == 1) {
            Long sid = ObjectUtil.getSid();
            Store store = storeService.selectById(sid);
            if (store != null) config.setPstype(store.getPstype());
        }

        json.setInfo(config);
        return json;
    }

    public static String getMachantId(String mcode) {

        if (Constants.MACHANT_MAP.keySet().size() == 0) {
            IMerchantService merchantService = (IMerchantService) SpringUtil.getBean("merchantService");
            List<Merchant> list = merchantService.selectByMap(new HashMap<String, Object>());
            for (Merchant item : list) {
                Constants.MACHANT_MAP.put(item.getMcode(), item.getId().toString());
            }
        }

        return Constants.MACHANT_MAP.get(mcode);
    }
}
